<?php

namespace app\admin\library;

use app\common\model\Admin;
use app\common\model\AuthRule;
use app\common\model\AuthGroup;

use szktor\Random;
use szktor\Tree;

use think\Db;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Session;
use think\facade\Request;
use think\facade\Url;
use think\facade\Env;
use think\Controller;

class Auth extends Controller
{
    protected $webCfg = ''; //站点配置
    protected $coustomCookiePre = 'supper_system'; //自己定义cookie前缀
    protected static $instance;

    public function __construct()
    {
        parent::__construct();
    }

    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }
    /**
     * 设置授权文件全局配置参数
     * @param array $arr 全局配置参数的数组
     */
    public function setAuthWebConfig($arr = '')
    {
        $this->webCfg = $arr;
		$this->webCfg['cookie_pre'] = $this->webCfg['cookie_pre'] . $this->coustomCookiePre;
    }
    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr)
        {
            return FALSE;
        }
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr))
        {
            return TRUE;
        }
        // 没找到匹配
        return FALSE;
    }

    /*
    *获取管理人员信息
    */
    public function getAdminInfo()
    {
		$ckArr = $this->getCookieAdminArr();
		if(!$ckArr) return false;
		$_arr = Admin::getAdminLoginInfo($ckArr['id'],$ckArr['pwd']);
		return $_arr;
    }
    /**
     * 管理人登录
     *
     * @param   string  $username   用户名
     * @param   string  $password   密码
     * @param   int     $keeptime   有效时长
     * @return  boolean
     */
    public function login($username, $password)
    {
		$map = ['a.admin_name' => trim($username), 'a.is_del' => '0'];
		$admin = Admin::alias('a')->join('auth_group b', 'a.group_id = b.id', 'left')
				->where($map)->field('a.*,b.name as g_name,b.rules as g_rules,b.status as g_status,b.remark as g_remark,b.index_page')
				->find();
		if(!$admin || !isset($admin['id']) || intval($admin['id']) <= 0)
		{
		    return ['err' => '1', 'msg' => '账号不存在'];
		}
		$now_time = time();
		$admin = $admin->toArray();
		if(intval($admin['status']) <= 0)
		{
			return ['err' => '2', 'msg' => '账号已禁用'];
		}
		if($admin['admin_pwd'] != Admin::encryptPassword($password,$admin['pwd_salt']))
		{
			return ['err' => '3', 'msg' => '登录密码错误'];
		}
		if(!$admin['group_id'])
		{
			return ['err' => '4', 'msg' => '权限配置错误，禁止登录'];
		}
		if(!$admin['g_status'])
		{
			return ['err' => '5', 'msg' => '权限组已被禁用，禁止登录'];
		}
		$r1 = $this->setLogined($admin['id'],$admin['admin_pwd']);
		if(!$r1)
		{
			return ['err' => '12', 'msg' => '登录失败，请重试'];
		}
		$r2 = Admin::where(['id' => $admin['id']])->update([
			'login_number' => intval($admin['login_number']+1), //累计登录次数
			'last_login_time' => $now_time, //最后登录时间
		]);
		return ['err' => '0', 'msg' => '登录成功，请稍候...'];
    }
    /*
    * 获取当前登录 return ['id' => '1', 'pwd' => 'dsgdsg'];
    */
    public function getCookieAdminArr()
    {
		$mid = (int)Session::get($this->webCfg['cookie_pre'] . '_admin_mid');
		$pwd = trim(Session::get($this->webCfg['cookie_pre'] . '_admin_key'));
		if($mid <= 0) $mid = (int)Cookie::get($this->webCfg['cookie_pre'] . '_admin_mid');
		if(!$pwd) $pwd = trim(Cookie::get($this->webCfg['cookie_pre'] . '_admin_key'));
		if((int)$mid <= 0 || !$pwd) return false;
		return ['id' => $mid, 'pwd' => $pwd];
    }
    /**
     * 设置一个用户登录
     */
    public function setLogined($mid = 0, $pwd = '')
    {
		if(!$mid || !$pwd) return false;
		Cookie::set($this->webCfg['cookie_pre'] . '_admin_mid', $mid);
		Cookie::set($this->webCfg['cookie_pre'] . '_admin_key', $pwd);
		Session::set($this->webCfg['cookie_pre'] . '_admin_mid', $mid);
		Session::set($this->webCfg['cookie_pre'] . '_admin_key', $pwd);
		return true;
    }
    /**
     * 注销登录
     */
    public function logout()
    {
		Cookie::set($this->webCfg['cookie_pre'] . '_admin_mid', '0');
		Cookie::set($this->webCfg['cookie_pre'] . '_admin_key', '');
		Session::set($this->webCfg['cookie_pre'] . 'member_id', '0');
		Session::set($this->webCfg['cookie_pre'] . '_admin_key', '');
		Cookie::delete($this->webCfg['cookie_pre'] . '_admin_mid');
		Cookie::delete($this->webCfg['cookie_pre'] . '_admin_key');
		Session::delete($this->webCfg['cookie_pre'] . '_admin_mid');
		Session::delete($this->webCfg['cookie_pre'] . '_admin_key');
		Cookie::clear();
		Session::destroy();
		return true;
    }
    /*
    * 当前的URL 权限验证
    */
    public function ruleCheck($_url = '',$group = [])
    {
      if(!$_url || !isset($group['g_rules'])) return false;
	  $gRules = trim($group['g_rules']);
      if(!$gRules || trim($gRules) == '*')
      {
        return true;
      }
      if($_url == $group['index_page']) //工作台页面
      {
        return true;
      }
      $_idArr = array_unique(explode(',',trim($gRules)));
      $map = [['id','IN',implode(',',$_idArr)],['status','=','1'],['module_type','=','admin']];   
      $list = AuthRule::where($map)->order('sort desc')->field('id,url')->select();
      if(!$list || count($list) <= 0)
      {
        return false;
      }
	  $list = $list->toArray();
      $_url = strtolower($_url);
      $res = false;
      foreach($list as $key => $val)
      {
         if(strpos(trim(strtolower($val['url'])),';') > 0)
         {
           $_tmpArr = explode(';',trim(strtolower($val['url'])));
           if(in_array($_url,$_tmpArr))
           {
              $res = true; 
              break;
           }
         }else{
           if(trim(strtolower($val['url'])) == strtolower($_url))
           {
              $res = true; 
              break;
           }
         }
      }
      return $res;
    }

    /*
    * 当前管理人员的菜单
    */
    public function getAdminMenu($admin = [])
    {
      if(!$admin || !$admin['g_rules']) return [];
      $_cache_name = md5('cms_adminmenu_newmenulist_' . $admin['id']);
      $arrList = Cache::get($_cache_name);
      if($arrList)
      {
		  return json_decode($arrList,true);
      }
      $arr = AuthRule::where(['module_type' => 'admin', 'type' => 'menu','status' => '1'])->order('sort desc')->field('id,pid,title,url,icon')->select()->toArray();
      if(isset($admin['index_page']) && $admin['index_page'])
      {
        foreach ($arr as $k => &$v){
          if(strtolower($v['url']) == '/admin/index/index')
          {
            $v['url'] = trim($admin['index_page']);
          }
        }
      }
	  $tree = Tree::instance();
	  $tree->init($arr);
	  $treeArr = $tree->getMenuTreeArray(0,'',$admin['g_rules']);
	  if(count($treeArr) <= 0) return [];
	  //保存一个月
	  Cache::set($_cache_name, json_encode($treeArr,JSON_UNESCAPED_UNICODE),['expire' => 86400*30]);
	  return $treeArr;
    }

}
